<template>
  <div>
    <el-input placeholder="请输入课程名" id="text" style="width: 90%" v-model="text"></el-input>
    <el-button :icon="Search" @click="handleSearch">搜索</el-button>
  </div>
  <div style="display: flex;margin-top: 10px">
    <el-button type="primary" :icon="Plus" @click="handleAdd" style="margin-left: 0;">添加数据</el-button>
    <el-button type="danger" :icon="Delete" style="margin-left: 80%" @click="handleDelList" v-if="multipleSelection.length>0">删除选中数据</el-button>
  </div>
  <div style="padding: 20px;">
    <el-table class="currentTable" :data="courses"
              @selection-change="handleSelectChange"
              @sort-change="handleSortChange"
              :header-cell-style="{ background: '#f6f9fa'}">
      <el-table-column type="selection"/>
      <!--el-table-column列-->
      <el-table-column prop="tno" label="教师号" sortable></el-table-column>
      <el-table-column prop="cno" label="课程号"></el-table-column>
      <el-table-column prop="cname" label="课程名"></el-table-column>
      <el-table-column prop="address" label="上课地点"></el-table-column>
      <el-table-column prop="time" label="上课时间"></el-table-column>
      <el-table-column prop="credit" label="学分"></el-table-column>
      <el-table-column prop="israte" label="开放评教">
        <template #default="{ row }">
          {{ row.israte === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="isopen" label="开放选课">
        <template #default="{ row }">
          {{ row.isopen === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="att" label="上课次数"></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="justify-content: center;margin-top: 8px"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" >
        <el-form-item label="教师号">
          <el-input v-model="form.tno"></el-input>
        </el-form-item>
        <el-form-item label="课程号">
          <el-input v-model="form.cno" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程名">
          <el-input v-model="form.cname"></el-input>
        </el-form-item>
        <el-form-item label="上课地点">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="上课时间">
          <el-input v-model="form.time"></el-input>
        </el-form-item>
        <el-form-item label="开放评教">
          <el-switch v-model="form.israte" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="开放选课">
          <el-switch v-model="form.isopen" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="学分">
          <el-input v-model="form.credit"></el-input>
        </el-form-item>
        <el-form-item label="上课次数">
          <el-input v-model="form.att"></el-input>
        </el-form-item>
        <el-form-item label="照片">
          <el-input v-model="form.photo"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogOk">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import axios from "axios";
import {onMounted, ref,computed} from "vue";
import {ElMessage,ElMessageBox} from "element-plus";
const courses=ref([])
const currentPage=ref(1)
const pageSize=ref(10)
const total=ref(0)
//组件挂载到DOM后执行后端数据加载
onMounted(()=>{
  getData();
})
const getData=()=>{
  axios.get("http://localhost:8080/course/findByPage",{
    params:{
      pageNum:currentPage.value,
      pageSize:pageSize.value
    }
  }).then(res=>{
    console.log(res.data.records)
    courses.value=res.data.records
    total.value=res.data.total
  }).catch(err=>{
    console.log(err)
  })
}
//切换每页显示条数
const handleSizeChange=(pagesize)=>{
  pageSize.value=pagesize
  getData();
}
//切换当前页码
const handleCurrentChange=(pageNum)=>{
  currentPage.value=pageNum
  getData();
}
const dialogVisible=ref(false)
const form=ref({});
const dialogType=ref('');
function handleEdit(row){//编辑按钮点击事件
  dialogVisible.value=true
  form.value={...row}
  dialogType.value='edit'
}
function handleAdd(){//添加按钮点击事件
  dialogVisible.value=true
  form.value={}
  dialogType.value='add'
}
const dialogTitle = computed(()=>{//弹窗标题
  return dialogType.value === 'add' ? '添加课程信息' : '编辑课程信息';
})
const dialogOk = ()=>{//弹窗确定按钮点击事件
  dialogVisible.value = false;
  if(dialogType.value==='add'){
    const newCourse={...form.value}
    axios.post("http://localhost:8080/course",newCourse)
        .then(response=>{
          ElMessage({
            type: 'success',
            message: '添加成功！',
          })
          getData();
        }).catch(error=>{
      console.log(error);
    })
  }
  else {
    const courseId=form.value.cno;
    const newCourse={...form.value}
    axios.put(`http://localhost:8080/course/${courseId}`,newCourse)
        .then(response=>{
          ElMessage({
            type: 'success',
            message: '修改成功！',
          })
          getData();
        }).catch(error=>{
      console.log(error);
    })
  }
}
// 删除行数据
const delRow = (row) => {
  // 获取要删除的用户的 ID
  const cId = row.cno;
  // 发送 HTTP DELETE 请求来删除用户
  axios.delete(`http://localhost:8080/course/${cId}`)
      .then(response => {
        localStorage.setItem('delete',JSON.stringify(response.data));
        getData();
      })
      .catch(error => {
        console.error(error);
      })
}
//处理删除按钮点击事件
function handleDelete(row) {
  ElMessageBox.confirm(
      '您确定要删除课程号为【' + row.cno + '】的数据吗?',
      '危险操作',

  ).then(() => {
    delRow(row)
    ElMessage({
      type: 'success',
      message: '完成删除！',
    })
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除!',
        })
      })
}
//多选事件
let multipleSelection = ref([]);
const handleSelectChange = (val) => {
  multipleSelection.value=[]
  val.forEach(item=>{
    multipleSelection.value.push(item.cno)
  })
}
//删除多条数据
const handleDelList=()=>{
  ElMessageBox.confirm(
      '您确定要删除选中的数据吗?',
      '危险操作',
      {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
  ).then(() => {
    const courseIds=multipleSelection.value;
    axios.delete('http://localhost:8080/courses',{
      method: 'post',
      data: JSON.stringify(courseIds), // 将数组转换为JSON字符串
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(response=>{
      getData();
      ElMessage({
        type: 'success',
        message: '完成批量删除！'
      })
    }).catch(error=>{
      console.log(error);
      ElMessage({
        type: 'error',
        message: '删除失败!'
      })
    }).catch(()=>{
      ElMessage({
        type: 'info',
        message: '取消删除!',
      })
    })
  })
}
// 搜索事件
const text=ref("");
const handleSearch=(val)=>{
  val=text.value;
  if(val.length>0){
    axios.get(`http://localhost:8080/courseByName/${val}`)
        .then(response=>{
          courses.value=response.data;
        }).catch(error=>{
      console.log(error);
    })
  }else {
    getData();
  }
}
// 排序事件
const handleSortChange = (sortData) => {
  const {prop, order} = sortData;
  courses.value=courses.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });

}
</script>


<style scoped>

</style>